<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="设备编号" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输设备编号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="设备类型" prop="code">
            <el-select v-model="queryParams.type" placeholder="请选择是否有效" clearable>
              <el-option
                v-for="dict in dict.type.device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:device:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:device:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:device:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-s-unfoldy" size="mini" @click="handleMove"
              v-hasPermi="['system:device:export']" :disabled="ids.length==0">移动</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设备名称" align="center" prop="name" />
          <el-table-column label="设备编号" align="center" prop="code" />
          <el-table-column label="设备状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.device_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="所属区域" align="center" prop="deptName" width="200"/>
          <el-table-column label="所属场地" align="center" prop="siteName" />
          <el-table-column label="状态" align="center" prop="state">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.common_status" :value="scope.row.state" />
            </template>
          </el-table-column>
          <el-table-column label="上线时间" align="center" prop="inlineTime" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:device:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:device:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
      <el-dialog width="600px" center title="选择经纬度" :visible.sync="innerVisible" :close-on-click-modal="false"
        append-to-body>
        <div>
          <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
            <!-- <el-input id="tipInput" v-model="poiKeywords" placeholder="请输入搜索名称"> -->
            <div>通过点击地图选择经纬度</div>
            <el-autocomplete class="inline-input" size="small" v-model="poiKeywords" :fetch-suggestions="querySearch"
              placeholder="请输入搜索名称" @select="handleSelect"></el-autocomplete>
          </div>
          <!-- <el-button slot="append" icon="el-icon-search" @click="searchKeyword" style="width:60px"></el-button> -->
          <!-- </el-input> -->
          <div ref="mapContainer" style="height:400px"></div>
          <div slot="footer" class="dialog-footer" align="right" style="margin-top:15px">
            <el-button type="primary" @click="confirmSelectAdress(1)">确 定</el-button>
            <el-button @click="confirmSelectAdress(0)">取 消</el-button>
          </div>
        </div>
      </el-dialog>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备类型" prop="code">
            <el-select v-model="form.type" placeholder="请选择是否有效" clearable>
              <el-option
                v-for="dict in dict.type.device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="生产厂家" prop="manufactor">
          <el-input v-model="form.manufactor" placeholder="请输入设备生产厂家" />
        </el-form-item>
        <el-form-item label="IP" prop="ipaddr" v-if="form.type == 'camera'">
          <el-input v-model="form.ipaddr" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="验证码" prop="validateCode" v-if="form.type == 'camera'">
          <el-input v-model="form.validateCode" placeholder="请输入设备验证码" />
        </el-form-item>
        <el-form-item label="端口号" prop="port"  v-if="form.type == 'camera'">
          <el-input v-model="form.port" placeholder="请输入设备端口号" />
        </el-form-item>
        <el-form-item label="账号" prop="loginName"  v-if="form.type == 'camera'">
          <el-input v-model="form.loginName" placeholder="请输入设备账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password"  v-if="form.type == 'camera'">
          <el-input v-model="form.password" placeholder="请输入设备密码" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请选择地址">
            <el-button slot="append" @click="POISearchDialog">选择经纬度</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.longitude" placeholder="经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.latitude" placeholder="纬度" />
        </el-form-item>
        <el-form-item label="所属区域" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属区域" />
        </el-form-item>
        <el-form-item label="所属场地" prop="siteId">
          <el-select v-model="form.siteId" placeholder="请选择场地">
            <el-option v-for="item in siteOptions" :label="item.name" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.state">
            <el-radio v-for="dict in dict.type.common_status" :key="dict.value" :label="parseInt(dict.value)">
              {{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="移动设备" :visible.sync="moveFlag" width="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="moveForm" :model="moveForm" label-width="100px">
        <el-form-item label="所属区域" prop="deptId">
          <treeselect v-model="moveForm.deptId" :options="deptOptions" :show-count="true" placeholder="请选择所属区域" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAreaMove">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const mapConfig = {
  securityJsCode: "b23c850a95afb3ca622bedf6efa527df",
  MAPKEY: "9b855993ebffd74a39d44888fff209f7",
};
import AMapLoader from "@amap/amap-jsapi-loader";
import { listDevice, getDevice, delDevice, addDevice, updateDevice ,areaMove,getSiteOptions} from "@/api/system/device";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Device",
  dicts: [ 'device_type',  'common_status'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      deptName: '',
      deptOptions: [],
      siteOptions:[],
      // 设备信息表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        // type: 'camera',
        subType: null,
        ipaddr: null,
        manufactor: null,
        channel: null,
        port: null,
        username: null,
        password: null,
        panelIpaddr: null,
        panelType: null,
        panelName: null,
        state: null,
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单参数
      form: {},
      moveForm:{},
      moveFlag:false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属区域不能为空", trigger: "change" }
        ],
        channel: [
          { required: true, message: "通道号不能为空", trigger: "change" }
        ],
        ipaddr: [
          { required: true, message: "IP地址不能为空", trigger: "blur" }
        ],
        port: [
          { required: true, message: "端口不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        siteId: [
          { required: true, message: "所属场地不能为空", trigger: "blur" }
        ],
      },
      innerVisible: false,
      poiKeywords: '',
      autoComplete: null,
      placeSearch: null,
      currentMarker: null,
      currentSelectAddress: null // 修改设备信息，当前选择的经纬度信息
    };
  },
  created() {
    this.getList();
    this.getTreeselect()
    this.getSiteOptions()
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    getSiteOptions(){
      getSiteOptions().then(res => {
        this.siteOptions = res.data ;
      })
    },
    confirmSelectAdress(type) {
      // 确定
      if (type === 1) {
        if (this.currentSelectAddress) {
          const result = this.currentSelectAddress
          const { formattedAddress, addressComponent } = result
          const { location, province, city, district } = addressComponent
          this.form.longitude = location.lng
          this.form.latitude = location.lat
          this.form.address = formattedAddress

          this.form.provinceCode = province
          this.form.cityCode = city
          this.form.adCode = district
        }
      }
      this.innerVisible = false
    },
    handleSelect(item) {
      this.placeSearch.setCity(item.adcode);
      this.placeSearch.search(item.name);
    },
    querySearch(queryString, cb) {
      this.autoComplete.search(queryString, (status, result) => {
        var tips = result.tips || [];
        tips = tips.map(it => {
          it.value = it.name
          return it
        })
        // 调用 callback 返回建议列表的数据
        cb(tips);
      })
    },
    POISearchDialog() {
      this.innerVisible = true
      this.currentSelectAddress = null
      this.poiKeywords = ''
      this.$nextTick(async () => {
        const AMap = await AMapLoader.load({
          key: mapConfig.MAPKEY, // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Geolocation"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        });

        this.map = new AMap.Map(this.$refs.mapContainer, {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 12, //初始化地图级别
          // center: [116.405467, 39.907761], //初始化地图中心点位置
        });
        AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation'], () => {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
          })

          function onComplete(res) {
            const pointer = [res.position.lng, res.position.lat]
            // data是具体的定位信息
            this.map.setCenter(pointer);
          }

          function onError(res) {
            // 定位出错
            console.error(res.message)
          }
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });
          var autoOptions = {
            //city 限定城市，默认全国
            city: '广州',
            input: "tipinput"
          };
          // 实例化AutoComplete
          const geocoder = new AMap.Geocoder()
          this.autoComplete = new AMap.AutoComplete(autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            map: this.map, // 展现结果的地图实例
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          this.placeSearch.on('markerClick', (e) => {
            const { location } = e.data
            geocoder.getAddress(location, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = location
                this.currentSelectAddress = result.regeocode
              }
            })
          })
          // 监听鼠标点击地图点，生成marker
          this.map.on('click', (ev) => {
            if (this.currentMarker) {
              this.map.remove(this.currentMarker);
            }
            const { lng, lat } = ev.lnglat
            var marker = new AMap.Marker({
              icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
              position: [lng, lat],
              offset: new AMap.Pixel(-10, -27),
            });
            this.currentMarker = marker
            this.map.add(marker);
            geocoder.getAddress(ev.lnglat, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = ev.lnglat
                this.currentSelectAddress = result.regeocode
              }
            })
          });
        })
      })

    },
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        type: '001',
        validateCode:null,
        subType: null,
        ipaddr: null,
        mac1: null,
        mac2: null,
        manufactor: null,
        protocol: null,
        channel: null,
        port: null,
        username: null,
        password: null,
        panelIpaddr: null,
        panelType: null,
        panelName: null,
        loginName:null,
        password:null,
        state: 1,
        siteId:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.getTreeselect()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    handleMove(){
      this.moveFlag = true ;
      this.moveForm = {
        ids : this.ids,
        deptId : null
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitAreaMove(){
      areaMove(this.moveForm)
      .then(response => {
        this.$modal.msgSuccess("操作成功");
        this.moveFlag = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备信息编号为"' + ids + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.el-tree{
  height:685px;
  overflow: auto;
}
</style>
